import Url from '../utils/url'
import Token from '../token/token'
import Config from '../utils/config'
import Util from '../../../assets/js/util'

export default {
  init: function (app, Router) {
    // localStorage.setItem('ACCESS_TOKEN', 'Bearer 1vQbXV0kqdpgP6CxrnzmjqtJNwE')
    // localStorage.setItem('REFRESH_TOKEN', 'qBAU1ElOaUAaNihDQp4QSFZnNFk')
    // localStorage.setItem('TOKEN_EXPIRES_TIME', '1713151626')
    Router.beforeEach((to, from, next) => {
      // 此处屏蔽，对应 config/config.js的【配置认证头部信息】
      // if (process.env.NODE_ENV === 'development') {
      //   next()
      //   return
      // }
      // 获取需要跳转页面路由
      app.config.globalProperties.$auth.config.baseUrl = Config.baseUrl + to.path
      // 授权获取token
      if (Url.getParam(to, 'code')) {
        Token.accestokenByCode(Url.getParam(to, 'code'))
      } else if (Url.getParam(to, 'logout') === 'yes') {
        // 登出
        Token.deleteToken()
      } else {
        // 判断是否登陆
        if (Token.isLogin()) {
          // 是否过期
          if (Token.isExpires()) {
            Token.refreshoken()
          } else {
            next()
          }
        } else {
          if (Config.grant_type === 'authorization_code') {
            let parentUrl
            if(window.parent?.location?.href) {
              parentUrl = window.parent.location.href.split('?')?.[0]
            }
            const currentUrl = parentUrl || window.location.href
            const url = Config.authUrl + '/oauth/authorize?response_type=code&client_id=' + Config.appId + '&redirect_uri=' + currentUrl + '&code_challenge_method=S256&code_challenge=' + Util.setSha256(Config.code)
            if(window.parent?.location?.href) {
              window.parent.location.href = url
            } else {
              window.location.href = url
            }
          } else if (Config.grant_type === 'password') {
            // 密码模式demo
            // var userInfo = prompt('username&password').split('&')
            // Token.accestokenByBasic(userInfo[0], userInfo[1], next)
          }
        }
      }
    })
  }
}
